package com.linln.admin.pcs.controller;


import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.*;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.persistence.criteria.Predicate;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 结算管理
 */
@Controller
@RequestMapping("/pcs/settlement")
public class SettlementController {

    @Autowired
    private AppService appService;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private PatientRepository patientRepository;
    @Autowired
    private PatientAdmissionRepository patientAdmissionRepository;
    @Autowired
    private OrderPortersRepository orderPortersRepository;
    @Autowired
    private OrderLogsRepository orderLogsRepository;
    @Autowired
    private  CompanyRepository companyRepository;

    @Autowired
    private OrderAmountsRepository orderAmountsRepository;
    @Autowired
    private CompanyParamRepository companyParamRepository;



    /**
     * 订单结算页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:settlement:index")
    public ResponseEntity<?> index(Model model, @EntityParam PatientAdmission patientAdmission) {
        return appService.layTable(patientAdmissionRepository, before -> {
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec1 = QuerySpec.matching();
                    querySpec1.withMatcherValue("orderStatus", QuerySpec.GT,"4")
                            .withMatcherValue("type", QuerySpec.EQUAL,"1")
                            .withMatcherValue("isSettled", QuerySpec.EQUAL,"2")
                            .withMatcherValue("settlementType", QuerySpec.EQUAL,"2");
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec1.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    List<Order> orders =orderRepository.findAll(QuerySpec.of(querySpec1));
                    List<Object> patient_admission_ids = new ArrayList<>();
                    for (Order order : orders) {
                        patient_admission_ids.add(order.getPatientAdmissionId());
                    }

                    QuerySpec querySpec = QuerySpec.matching();
//                    querySpec.withMatcher("name", QuerySpec.LIKE)
//                                    .withMatcherValue("admissionStatus", QuerySpec.EQUAL,"2");
                    querySpec.withMatcher("name", QuerySpec.LIKE);
                    querySpec.withMatcherIn("id", patient_admission_ids);


                    return QuerySpec.of(querySpec);
                },

                "/pcs/settlement/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        // 统计对应住院记录期间产生的未结算订单的金额
                        PatientAdmission data = (PatientAdmission) item;
                        try {
                            data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        QuerySpec querySpec = QuerySpec.matching();
                        querySpec.withMatcherValue("patientAdmissionId", QuerySpec.EQUAL,data.getId().toString())
                                .withMatcherValue("type", QuerySpec.EQUAL,"1")
                                .withMatcherValue("orderStatus", QuerySpec.GT,"4")
                                .withMatcherValue("isSettled", QuerySpec.EQUAL,"2")
                                .withMatcherValue("settlementType", QuerySpec.EQUAL,"2");
                        List<Order> orders =orderRepository.findAll(QuerySpec.of(querySpec));
                        Double amount = 0.0;
                        if (orders.size()>0) {
                            for (Order order : orders) {
                                amount += order.getTotal();
                            }
                        }
                        data.setAmount(amount);
                    });
                }

        );

    }

    //订单结算操作
    @RequestMapping("/settled")
    @RequiresPermissions("pcs:settlement:settled")
    public ResponseEntity<?> settled(Model model,@EntityParam PatientAdmission patientAdmissionParam) {
        String method = HttpServletUtil.getMethod();
        if (method.equals("GET")) {
            String patientAdmissionId = HttpServletUtil.getParameter("id");
            PatientAdmission patientAdmission = patientAdmissionRepository.getById(Long.valueOf(patientAdmissionId));
            model.addAttribute("patientAdmission", patientAdmission);
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("patientAdmissionId", QuerySpec.EQUAL,patientAdmissionId)
                    .withMatcherValue("type", QuerySpec.EQUAL,"1")
                    .withMatcherValue("orderStatus", QuerySpec.GT,"4")
                    .withMatcherValue("isSettled", QuerySpec.EQUAL,"2")
                    .withMatcherValue("settlementType", QuerySpec.EQUAL,"2");
            List<Order> orders =orderRepository.findAll(QuerySpec.of(querySpec));

            List<Object> order_ids = new ArrayList<>();
            for (Order order : orders) {
                order_ids.add(order.getId());
                order.setCreateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",order.getCreateTime()));
            }

            model.addAttribute("orders", orders);
            //预缴金额
            double increase = 0.0;
            //消费金额
            double reduce = 0.0;
            if (order_ids.size()>0) {
                QuerySpec querySpec1 = QuerySpec.matching();
                querySpec1.withMatcherIn("orderId", order_ids);
                List<OrderAmounts> orderAmounts = orderAmountsRepository.findAll(QuerySpec.of(querySpec1));
                for (OrderAmounts orderAmount : orderAmounts) {
                   if(orderAmount.getType()==2){
                       increase += orderAmount.getIncrease();
                   }
                   if(orderAmount.getType()==1){
                       reduce += orderAmount.getReduce();
                   }
                }
            }
            //补缴金额
            double prepay = reduce -increase;
            model.addAttribute("increase",increase);
            model.addAttribute("reduce",reduce);
            model.addAttribute("prepay",prepay);

            //查询收款码
            User user = ShiroUtil.getSubject();
            if (user.getType()!=null&&user.getType().equals("2")) {
                Long companyId = user.getCompanyId();
                QuerySpec querySpec1 = QuerySpec.matching();
                querySpec1.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                List<CompanyParam> companyParams =  companyParamRepository.findAll(QuerySpec.of(querySpec1));
                if(companyParams.size()>0){
                    CompanyParam companyParam = companyParams.get(0);
                    model.addAttribute("payErw", companyParam.getPayErw());
                }
            }




            // 必须手动渲染模板
            Context context = new Context();
            // 将数据加入到 Thymeleaf 上下文中
            context.setVariables(model.asMap());
            // 使用 Thymeleaf 渲染模板
            StringWriter writer = new StringWriter();
            thymeleafViewResolver.getTemplateEngine().process("/pcs/settlement/form", context, writer);

            return ResponseEntity.ok( writer.toString());
        }else{
            List<Long> orderIds = patientAdmissionParam.getOrderIds();
            for (Long orderId : orderIds) {
                Order order = orderRepository.getById(orderId);
                order.setIsSettled(1);
                order.setSettledType(patientAdmissionParam.getSettledType());
                orderRepository.save(order);
            }
            PatientAdmission patientAdmission = patientAdmissionRepository.getById(patientAdmissionParam.getId());
            patientAdmission.setSettledTime(new Date());
            patientAdmission.setIsSettled(1);
            patientAdmission.setSettledType(patientAdmissionParam.getSettledType());
            patientAdmission.setIncrease(patientAdmissionParam.getIncrease());
            patientAdmission.setReduce(patientAdmissionParam.getReduce());
            patientAdmission.setPrepay(patientAdmissionParam.getPrepay());
            patientAdmissionRepository.save(patientAdmission);

            return ResponseEntity.ok(ResultVoUtil.success("成功"));
        }

    }

    //结算明细
    @RequestMapping("/list")
    @RequiresPermissions("pcs:settlement:list")
    public ResponseEntity<?> list(Model model, @EntityParam PatientAdmission patientAdmission) {
        return appService.layTable(patientAdmissionRepository, before -> {
                    Integer year = HttpServletUtil.getParameterInt("year",0);
                    if(year==0){
                        //获取当前年
                        year = LocalDate.now().getYear();;
                    }
                    Long companyId = 1L;
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        companyId = user.getCompanyId();
                    }
                    //陪护订单金额
                    BigDecimal careOrderAmount = orderRepository.findTotalAmountByYear(year,companyId,1);
                    //陪诊订单金额
                    BigDecimal consultationOrderAmount = orderRepository.findTotalAmountByYear(year,companyId,2);
                    //陪检订单金额
                    BigDecimal inspectionOrderAmount = orderRepository.findTotalAmountByYear(year,companyId,3);
                    model.addAttribute("careOrderAmount",careOrderAmount);
                    model.addAttribute("consultationOrderAmount",consultationOrderAmount);
                    model.addAttribute("inspectionOrderAmount",inspectionOrderAmount);
                    // 添加模板变量
                    return model;

                },

                after -> {



                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("name", QuerySpec.LIKE);
                            //.withMatcherValue("admissionStatus", QuerySpec.EQUAL,"2");


                    return QuerySpec.of(querySpec);
                },

                "/pcs/settlement/list",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        // 统计对应住院记录期间产生的所有订单的金额
                        PatientAdmission data = (PatientAdmission) item;

                        try {
                            data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }

                        QuerySpec querySpec = QuerySpec.matching();
                        querySpec.withMatcherValue("patientAdmissionId", QuerySpec.EQUAL,data.getId().toString())
                                //.withMatcherValue("type", QuerySpec.EQUAL,"1")
                                .withMatcherValue("orderStatus", QuerySpec.GT,"4");
                        User user = ShiroUtil.getSubject();
                        if (user.getType()!=null&&user.getType().equals("2")) {
                            Long companyId = user.getCompanyId();
                            querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                        }
                        List<Order> orders =orderRepository.findAll(QuerySpec.of(querySpec));
                        Double amount = 0.0;
                        if (orders.size()>0) {
                            for (Order order : orders) {
                                amount += order.getTotal();
                            }
                        }
                        data.setAmount(amount);
                    });
                }

        );

    }


    @RequestMapping("/detail")
    @RequiresPermissions("pcs:settlement:detail")
    public String detail(Model model) {
        Integer id = HttpServletUtil.getParameterInt("id",0);
        if(id!=0){
            PatientAdmission patientAdmission = patientAdmissionRepository.getById(id.longValue());
            patientAdmission.setAdmissionTimeStr(patientAdmission.getAdmissionTime());
            patientAdmission.setDischargeTimeStr(patientAdmission.getDischargeTime());
            Patient patient = patientRepository.getById(patientAdmission.getPatientId());
            patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
            model.addAttribute("patient",patient);
            model.addAttribute("patientAdmission",patientAdmission);
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("patientAdmissionId", QuerySpec.EQUAL,patientAdmission.getId().toString())
                    .withMatcherValue("orderStatus", QuerySpec.NOT_EQUAL,"-1");
            List<Order> orders =orderRepository.findAll(QuerySpec.of(querySpec));
            orders.forEach(item->{
                item.setCreateTimeStr(HelperUtil.dateFormat(item.getCreateTime(),"yyyy-MM-dd"));
                item.setCompanyName(companyRepository.getById(item.getCompanyId()).getName());
            });
            model.addAttribute("orders",orders);

        }
        return "/pcs/settlement/detail";
    }




}
